package io.renren.modules.sp.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.listener.SpUserImportListener;
import io.renren.common.page.PageData;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sp.dto.SpUserDTO;
import io.renren.modules.sp.dto.SpUserImport;
import io.renren.modules.sp.excel.SpUserExcel;
import io.renren.modules.sp.service.SpTeamService;
import io.renren.modules.sp.service.SpUserService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
* 用户
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-21
*/
@RestController
@RequestMapping("sp/spuser")
@Api(tags="用户")
public class SpUserController {
    @Autowired
    private SpUserService spUserService;
    @Autowired
    private SpTeamService spTeamService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    // @RequiresPermissions("sp:spuser:page")
    public Result<PageData<SpUserDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        //判断是否是省赛管理员
        String userType = sysUserService.getSysUserType();
        if("3".equals(userType)){
            //姓名和身份证号必须不为空
            String realName = (String)params.get("realName");
            String idCard = (String)params.get("idCard");
            if(StringUtils.isNotBlank(realName) && StringUtils.isNotBlank(idCard)){

            }else{
                PageData<SpUserDTO> page = new PageData<SpUserDTO>(null, 0L);
                return new Result<PageData<SpUserDTO>>().ok(page);
            }
        }

        PageData<SpUserDTO> page = spUserService.page(params);
        //查询代表队信息
        for (SpUserDTO spUserDTO : page.getList()) {
            Map<String, Object> teamInfo = spTeamService.queryTeamInfo(spUserDTO.getId());
            if(teamInfo == null){
                continue;
            }
            spUserDTO.setTeamName((String)teamInfo.get("team_name"));
            spUserDTO.setTeamCompany((String)teamInfo.get("company"));
            spUserDTO.setTeamLeader((String)teamInfo.get("leader"));
            spUserDTO.setTeamLeaderPhone((String)teamInfo.get("uphone"));
        }
        return new Result<PageData<SpUserDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    //@RequiresPermissions("sp:spuser:info")
    public Result<SpUserDTO> get(@PathVariable("id") Long id){
        SpUserDTO data = spUserService.get(id);
        Map<String, Object> teamInfo = spTeamService.queryTeamInfo(data.getId());
        if(teamInfo != null){
            data.setTeamName((String)teamInfo.get("team_name"));
            data.setTeamCompany((String)teamInfo.get("company"));
            data.setTeamLeader((String)teamInfo.get("leader"));
            data.setTeamLeaderPhone((String)teamInfo.get("phone"));
        }
        return new Result<SpUserDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    //@RequiresPermissions("sp:spuser:save")
    public Result save(@RequestBody SpUserDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        spUserService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    //@RequiresPermissions("sp:spuser:update")
    public Result update(@RequestBody SpUserDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        //判断手机号是否重复


        spUserService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    //@RequiresPermissions("sp:spuser:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        spUserService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    //@RequiresPermissions("sp:spuser:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SpUserDTO> list = spUserService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, "用户", list, SpUserExcel.class);
    }

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("import")
    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataType="file")
    public Result importCertificate(@RequestParam("file") MultipartFile file) throws Exception {
        Result result = new Result();
        List<SpUserImport> list = new ArrayList<>();
        //大批量excel数据导入
        EasyExcel.read(file.getInputStream(), SpUserImport.class,
                new SpUserImportListener(spUserService, result, list)).sheet().doRead();

        for(SpUserImport userExcel : list){
            if(StringUtils.isNotEmpty(userExcel.getCheckMsg())) {
                String errorCode = UUID.randomUUID().toString();
                redisUtils.set(errorCode, JSONArray.toJSONString(list), 1000);
                return new Result().ok(errorCode);
            }
        }
        return result;
    }


    @GetMapping("exportError1")
    public void export1(String errorCode,HttpServletResponse response) throws Exception {
        String json = (String) redisUtils.get(errorCode);
        redisUtils.delete(errorCode);
        if (json != null) {
            List<SpUserImport> list = JSONArray.parseArray(json, SpUserImport.class);
            /*List<SpMatchItemTeamSingleImport> listSingle = new ArrayList<>();
            for (SpUserImport item : list) {
                SpMatchItemTeamSingleImport itemSingle = new SpMatchItemTeamSingleImport();
                BeanUtil.copyProperties(item,itemSingle);
                listSingle.add(itemSingle);
            }*/
            ExcelUtils.exportExcelToTarget(response, "失败原因", "用户", list, SpUserImport.class);
        }
    }

}
